#include <QCoreApplication>
#include <QHttpServer>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonParseError>
#include <QTcpServer>
#include <QHttpServerResponse>
#include <QSqlDatabase>
#include <QSqlError>
#include <QSqlQuery>
#include <QSqlRecord>
#include <QFile>

//将record转换成json对象
QJsonObject recordToJsonObject(const QSqlRecord& record){

    if (record.isEmpty())
        return QJsonObject();

    QJsonObject r;
    for(int i=0;i<record.count();i++){

        r[record.fieldName(i)] = record.value(i).toString();
    }

    return r;

}




int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    //连接数据库
    auto db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("127.0.0.1");
    db.setUserName("root");
    db.setPassword("Stallman7*");
    db.setDatabaseName("world");
    if(!db.open()){
        qDebug() << db.lastError().text();
        return 0;
    }
    else
        qDebug() << "数据连接成功!";

    QHttpServer server;


    server.route("/",[](){
        return QHttpServerResponse("text/html","<h1>Hello Wq Big Ass I love your big ass!</h1>");
    });
    server.route("/favicon.ico",[](){
        qDebug() << "/favicon.ico";
        return QHttpServerResponse::fromFile(":/favicon.ico");
    });

    //带参数的路由 通过id字段获取一条记录 表中必须有一个id且唯一
    server.route("/search/<arg>/<arg>/<arg>",  [] (const QString dbname,const QString tbname,const int id)
                 {


                     //获取数据
                     QString sql = QString("SELECT * FROM %1.%2 WHERE id=%3;").arg(dbname,tbname).arg(id);
                     QSqlQuery query;
                     auto ret = query.exec(sql);
                     if (!ret){
                         qDebug() << query.lastError().text();
                         return QHttpServerResponse(query.lastError().text());
                     }
                     else
                     {

                         if(query.first())
                         {
                             auto record =  query.record();
                            //表格形式
                             QString thead , tbody;
                             for(int i=0;i<record.count();i++){
                                 thead += QString("<th>%1</th>").arg(record.fieldName(i));
                                 tbody += QString("<td>%1</td>").arg(record.value(i).toString());
                             }

                             QFile f(":/city.html");
                             f.open(QFile::ReadOnly);
                             QString res = QString(f.readAll()).arg(thead,tbody);


                             return QHttpServerResponse("text/html",res.toUtf8());

                             // auto jsonObj = recordToJsonObject(record);
                             // return QString(QJsonDocument(jsonObj).toJson(QJsonDocument::Indented));
                         }
                         else
                             return QHttpServerResponse("no record for");
                     }



                 });


    //启动服务器
    auto tcpserver = new QTcpServer();
    if (!tcpserver->listen(QHostAddress::Any,8888) || !server.bind(tcpserver)) {
        delete tcpserver;
        return -1;
    }
    qDebug() << "Listening on port" << tcpserver->serverPort();


    return a.exec();
}
